package com.sinog.basic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sinog.basic.entity.AuthUser;
import com.sinog.basic.mapper.DepartmentMapper;
import com.sinog.basic.mapper.SystemCodeMapper;
import com.sinog.basic.mapper.UserMapper;
import com.sinog.basic.mapper.common.CommonBasicMapper;
import com.sinog.basic.service.DepartmentService;
import com.sinog.core.domain.Department;
import com.sinog.core.domain.SystemCode;
import com.sinog.core.domain.User;
import com.sinog.core.domain.UserInterFaceEntity;
import com.sinog.core.util.JsonUtil;
import com.sinog.core.util.PinYinUtils;
import com.sinog.core.utilbean.Constants;
import com.sinog.core.utilbean.Result;
import com.sinog.core.utilbean.ReturnCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @desc 系统管理 - 部门管理 - 部门管理 - DepartmentServiceImpl
 * @author -
 * @date -
 */
@Service
@Slf4j
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper,Department> implements DepartmentService {

    @Resource
    private DepartmentMapper departmentMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private SystemCodeMapper systemCodeMapper;
    @Resource
    private CommonBasicMapper commonBasicMapper;
    /**
     * 初始密码
     */
    @Value("${gkzx.azbj.security.user-default-password-reset}")
    private String password;

    /**
     * 系统管理 - 部门管理 - 部门管理 - 保存部门信息
     * @param department department
     * @return Result
     */
    @Override
    public Result save(String department) {
        Department bean = JsonUtil.toBean(department,Department.class);
        String pid = bean.getPid();
        String level = bean.getLevel();
        String provinceCode = pid.substring(0,2);
        String maxDeptId = departmentMapper.selectMaxDeptId(level,pid);
        Date date = new Date();
        if("".equals(bean.getId()) || null == bean.getId()) {
            //直辖市处理
            if(Constants.XzqhCode.BEIJING.equals(pid) || Constants.XzqhCode.CHONGQING.equals(pid) || Constants.XzqhCode.SHANGHAI.equals(pid) || Constants.XzqhCode.TIANJIN.equals(pid)) {
                if(Constants.OrgLevel.LEVEL_QXSFJ.equals(level)) {
                    //直辖市区县司法局-->查询直辖市下所有区县司法局最大部门编号+1
                    int i;
                    if(null == maxDeptId || maxDeptId.isEmpty()) {
                        i = Integer.parseInt(pid) + 1;
                    } else {
                        i = Integer.parseInt(maxDeptId) + 1;
                    }
                    int noExistsId = getNoExistsId(i,1);
                    bean.setId(String.valueOf(noExistsId));
                } else if(Constants.OrgLevel.LEVEL_SSJ.equals(level)) {
                    //省社矫机构-->如没有取省份前两位+000000
                    if(null == maxDeptId || maxDeptId.isEmpty()) {
                        bean.setId(provinceCode + "000000");
                    } else {
                        return Result.failure(ReturnCode.SAVE_FAILED_SJ);
                    }
                } else if(Constants.OrgLevel.LEVEL_QXSJ.equals(level)) {
                    //区县社矫机构-->取上级地市社矫机构+1000
                    int i;
                    if(null == maxDeptId || maxDeptId.isEmpty()) {
                        i = Integer.parseInt(pid) + 100;
                    } else {
                        i = Integer.parseInt(maxDeptId) + 100;
                    }
                    int noExistsId = getNoExistsId(i,100);
                    bean.setId(String.valueOf(noExistsId));
                } else if(Constants.OrgLevel.LEVEL_DSSJ.equals(level)) {
                    //直辖市教育矫治局-->取直辖市前两位+000
                    if(null == maxDeptId || maxDeptId.isEmpty()) {
                        bean.setId(provinceCode + "000");
                    } else {
                        int i = Integer.parseInt(maxDeptId) + 1;
                        int noExistsId = getNoExistsId(i,1);
                        bean.setId(String.valueOf(noExistsId));
                    }
                } else if(Constants.OrgLevel.LEVEL_JGZD.equals(level)) {
                    //直辖市 监管支队-->取监管总队+100
                    int i;
                    if(null == maxDeptId || maxDeptId.isEmpty()) {
                        i = Integer.parseInt(pid) + 100;
                    } else {
                        i = Integer.parseInt(maxDeptId) + 100;
                    }
                    int noExistsId = getNoExistsId(i,100);
                    bean.setId(String.valueOf(noExistsId));
                }
            } else {
                if(Constants.OrgLevel.LEVEL_DSSFJ.equals(level)) {
                    //省地市司法局-->查询省份下所有地市司法局最大部门编号+100
                    int i;
                    if(null == maxDeptId || maxDeptId.isEmpty()) {
                        i = Integer.parseInt(pid) + 100;
                    } else {
                        i = Integer.parseInt(maxDeptId) + 100;
                    }
                    int noExistsId = getNoExistsId(i,100);
                    bean.setId(String.valueOf(noExistsId));
                } else if(Constants.OrgLevel.LEVEL_QXSFJ.equals(level)) {
                    //省区县司法局-->查询省份下所有区县司法局最大部门编号+1
                    int i;
                    if(null == maxDeptId || maxDeptId.isEmpty()) {
                        i = Integer.parseInt(pid) + 1;
                    } else {
                        i = Integer.parseInt(maxDeptId) + 1;
                    }
                    int noExistsId = getNoExistsId(i,1);
                    bean.setId(String.valueOf(noExistsId));
                } else if(Constants.OrgLevel.LEVEL_SSJ.equals(level)) {
                    //省社矫机构-->如没有取省份前两位+000000
                    if(null == maxDeptId || maxDeptId.isEmpty()) {
                        bean.setId(provinceCode + "000000");
                    } else {
                        return Result.failure(ReturnCode.SAVE_FAILED_SJ);
                    }
                } else if(Constants.OrgLevel.LEVEL_DSSJ.equals(level)) {
                    //地市社矫机构-->如没有取省级社矫机构+10000
                    if(null == maxDeptId || maxDeptId.isEmpty()) {
                        int i = Integer.parseInt(pid) + 10000;
                        bean.setId(String.valueOf(i));
                    } else {
                        int i = Integer.parseInt(maxDeptId) + 10000;
                        int noExistsId = getNoExistsId(i,10000);
                        bean.setId(String.valueOf(noExistsId));
                    }
                } else if(Constants.OrgLevel.LEVEL_JGZD.equals(level)) {
                    //地市（区县）监管支队-->取监管总队+100
                    int i;
                    if(null == maxDeptId || maxDeptId.isEmpty()) {
                        i = Integer.parseInt(pid) + 100;
                    } else {
                        i = Integer.parseInt(maxDeptId) + 100;
                    }
                    int noExistsId = getNoExistsId(i,100);
                    bean.setId(String.valueOf(noExistsId));
                } else if(Constants.OrgLevel.LEVEL_QXSJ.equals(level)) {
                    //区县社矫机构-->取上级地市社矫机构+1000
                    int i;
                    if(null == maxDeptId || maxDeptId.isEmpty()) {
                        i = Integer.parseInt(pid) + 100;
                    } else {
                        i = Integer.parseInt(maxDeptId) + 100;
                    }
                    int noExistsId = getNoExistsId(i,100);
                    bean.setId(String.valueOf(noExistsId));
                }
            }
            if(Constants.OrgLevel.LEVEL_SFS.equals(level)) {
                //司法所-->取上级单位编号+001
                maxDeptId = departmentMapper.selectMaxDeptIds(provinceCode,level);
                if(null == maxDeptId || maxDeptId.isEmpty()) {
                    bean.setId(pid + "001");
                } else {
                    bean.setId(maxDeptId);
                }
            } else if(Constants.OrgLevel.LEVEL_JY.equals(level)) {
                //监狱-->取省级单位编号前两位+01
                maxDeptId = departmentMapper.selectMaxDeptIds(provinceCode,level);
                if(null == maxDeptId || maxDeptId.isEmpty()) {
                    bean.setId(provinceCode + Constants.NumberStr.NUM_STR_ZERO_ONE);
                } else {
                    bean.setId(maxDeptId);
                }
            } else if(Constants.OrgLevel.LEVEL_SJZX.equals(level)) {
                //05-->社区矫正-->取区县社矫机构+1
                if(null == maxDeptId || maxDeptId.isEmpty()) {
                    int i = Integer.parseInt(pid) + 1;
                    bean.setId(String.valueOf(i));
                } else {
                    int i = Integer.parseInt(maxDeptId) + 1;
                    bean.setId(String.valueOf(i));
                }
            } else if(Constants.OrgLevel.LEVEL_KSS.equals(level)) {
                //02-->看守所-->因需要生成罪犯编号，与社矫编号同为5位，编号递增
                maxDeptId = departmentMapper.selectMaxDeptIdSpecial(provinceCode);
                if(null == maxDeptId || maxDeptId.isEmpty()) {
                    bean.setId(provinceCode + "001");
                } else {
                    bean.setId(maxDeptId);
                }
            }
        }
        //1、判断是新增还是修改
        Department department1 = departmentMapper.selectByDeptId(bean.getId());
        List<String> pids = departmentMapper.selectCache(bean.getId());
        //增加机构时需要增加azbj_rs
        if(null == department1) {
            new Thread(() -> {
                commonBasicMapper.deleteAzbjRs(bean.getId());
                ArrayList<String> items = new ArrayList<>(16);
                items.add("azbjrs");
                items.add("bjjdsl");
                items.add("dxjrs");
                items.add("dxjzddxrs");
                items.add("jywxjrs");
                items.add("shzzsl");
                items.add("slrs");
                items.add("wpgrs");
                items.add("wxjrs");
                items.add("ysfrs");
                items.add("zdbjdxrs");
                items.add("zyzsl");
                for(String item : items) {
                    commonBasicMapper.saveAzbjRs(bean.getId(),item);
                }
            },"azbj-rs-thread").start();
        }
        boolean tag = bean.insertOrUpdate();
        this.saveSj(bean);
        this.createAccount(bean);
        new Thread(() -> {
            log.debug("异步处理机构缓存");
            if(null != department1) {
                //3、修改
                //原来全部父机构删除该ID及全部子机构ID
                log.info("old::::{}",pids);
                List<String> childs = departmentMapper.selectChilds(bean.getId());
                List<Map<String,String>> caches = commonBasicMapper.selectCacheByIds(pids);
                for(Map<String,String> map : caches) {
                    String childid = map.get("childid");
                    for(String str : childs) {
                        childid = childid.replace("," + str + ",",",");
                    }
                    commonBasicMapper.updateCacheByIdDepartment(map.get("id"),childid);
                }
                //新全部父机构添加该ID及全部子机构ID
                List<String> newPids = departmentMapper.selectCache(bean.getPid());
                log.info("new::::" + newPids);
                List<Map<String,String>> newCaches = commonBasicMapper.selectCacheByIds(newPids);
                for(Map<String,String> map : newCaches) {
                    String childid = map.get("childid");
                    for(String str : childs) {
                        childid = new StringBuilder(16).append(childid).append(str).append(",").toString();
                    }
                    commonBasicMapper.updateCacheByIdDepartment(map.get("id"),childid);
                }
                log.debug("处理tbsys_code,修改街道那一级");
                SystemCode systemCode1 = new SystemCode();
                String adminCodeName = bean.getName().replaceAll("司法所|司法局|监狱|看守所|监管支队","");
                systemCode1.setCodeName(adminCodeName);
                systemCode1.setCodeType(Constants.CodeType.CODE_ZHRMGHG_XZQH_DM);
                systemCode1.setCodeTypeName("中华人民共和国行政区划代码");
                systemCode1.setCodeId(bean.getId());
                systemCode1.setPcodeId(bean.getPid());
                systemCode1.setCodeDescribe("无");
                systemCode1.setCreateUserId("sys");
                systemCode1.setCreateTime(date);
                systemCode1.setSn(null == systemCodeMapper.getSystemCodeMaxSn() ? 1 : systemCodeMapper.getSystemCodeMaxSn());
                systemCodeMapper.updateSystemCode(systemCode1);
            } else {
                //2、新增
                //添加本机构ID的数据
                int i = commonBasicMapper.insertCacheDepartment(bean.getId());
                if(0 < i) {
                    //把全部上级追加本机构ID
                    List<String> pidss = departmentMapper.selectCache(bean.getPid());
                    List<Map<String,String>> caches = commonBasicMapper.selectCacheByIds(pidss);
                    for(Map<String,String> map : caches) {
                        String childid = map.get("childid");
                        childid = childid + bean.getId() + ",";
                        commonBasicMapper.updateCacheByIdDepartment(map.get("id"),childid);
                    }
                }
                log.debug("处理tbsys_code");
                //添加第四级的街道乡镇到tbsys_code
                SystemCode systemCode1 = new SystemCode();
                String adminCodeName = bean.getName().replaceAll("司法所|司法局|监狱|看守所|监管支队","");
                systemCode1.setCodeName(adminCodeName);
                systemCode1.setCodeId(bean.getId());
                systemCode1.setPcodeId(bean.getPid());
                systemCode1.setCodeType(Constants.CodeType.CODE_ZHRMGHG_XZQH_DM);
                systemCode1.setCreateUserId("sys");
                systemCode1.setCreateTime(date);
                systemCode1.setCodeTypeName("中华人民共和国行政区划代码");
                systemCode1.setSn(null == systemCodeMapper.getSystemCodeMaxSn() ? 1 : systemCodeMapper.getSystemCodeMaxSn());
                boolean insertSystemCode = systemCodeMapper.insertSystemCode(systemCode1);
                if(insertSystemCode) {
                    log.debug("添加tbsys_code成功");
                } else {
                    log.debug("添加tbsys_code失败");
                }
                log.debug("异步处理用户机构缓存");
                //2、新增
                //判断该用户的departId是否在用户机构缓存表存在
                Long aLong = userMapper.checkAccount(bean.getId());
                if(0 >= aLong) {
                    new Thread(() -> {
                        log.debug("异步处理用户机构缓存");
                        //2、新增
                        //判断该用户的departId是否在用户机构缓存表存在
                        Integer i1 = commonBasicMapper.existDepartId(bean.getId());
                        //不存在，添加一条
                        if(null == i1) {
                            int k = commonBasicMapper.insertCache(bean.getId());
                            if(0 < k) {
                                //把全部上级追加本机构ID
                                List<String> pidss = departmentMapper.selectCache(bean.getPid());
                                List<Map<String,String>> caches = commonBasicMapper.selectCacheByIds(pidss);
                                for(Map<String,String> map : caches) {
                                    String childid = map.get("childid");
                                    childid = childid + bean.getPid() + ",";
                                    commonBasicMapper.updateCacheById(map.get("id"),childid);
                                }
                            }
                        }
                    },"Thread-user-1").start();
                }
            }
        },"Thread-org-1").start();
        if(tag) {
            return Result.success("保存成功");
        }
        return Result.failure(ReturnCode.SAVE_FAILED);
    }

    /**
     * 系统管理 - 部门管理 - 部门管理 - 批量删除部门
     * @param ids ids
     * @param id id
     * @return Result
     */
    @Override
    public Result deleteBatch(String[] ids,String id) {
        Department department = new Department();
        //查询本机构全部父机构ID集合
        List<String> pids = departmentMapper.selectCache(id);
        boolean success = department.delete(new QueryWrapper<Department>().in("id",ids));
        ArrayList<String> depIdList = new ArrayList<>();
        if(ids != null && ids.length > 0) {
            for(String depId : ids) {
                depIdList.add(depId + "X");
            }
            department.delete(new QueryWrapper<Department>().in("id",depIdList));
        }
        if(success) {
            new Thread(() -> {
                //1、根据ids删除 tbsys_department_child_cache表
                List<String> childs = departmentMapper.selectChilds(id);
                if(0 < childs.size()) {
                    department.delete(new QueryWrapper<Department>().in("id",childs));
                }
                commonBasicMapper.deleteCacheByIds(ids);
                //2、将本机构ID及全部子机构ID 在本机构的全部父机构中删除
                List<Map<String,String>> caches = commonBasicMapper.selectCacheByIds(pids);
                for(Map<String,String> map : caches) {
                    String childid = map.get("childid");
                    for(String str : Objects.requireNonNull(ids)) {
                        childid = childid.replace("," + str + ",",",");
                    }
                    commonBasicMapper.updateCacheByIdDepartment(map.get("id"),childid);
                }
            },"Thread-org-2").start();
            //删除tbsys_code和azbj_rs
            new Thread(() -> {
                //1.根据id,删除tbsys_code的表记录
                systemCodeMapper.deleteTbsysCodeById(id);
                //2.删除azbj_rs表记录
                commonBasicMapper.deleteAzbjRs(id);
            },"Thread-admin-code").start();
            return Result.success();
        }
        return Result.failure(ReturnCode.DELETE_FAILED);
    }

    /**
     * 系统管理 - 部门管理 - 部门管理 - 获取点击节点的部门信息
     * @param id id
     * @param pid pid
     * @param type 查询类型、1:(loadTree),2:(loadTreeNoParent),3:(getDepartInfo)
     * @return Result
     */
    @Override
    public Result getDepartInfo(String id,String pid,String type) {
        return Result.success(departmentMapper.getDepartInfo(id,pid,type));
    }

    /**
     * 系统管理 - 部门管理 - 部门管理 - 获取下级机构类型下拉
     * @param deptId deptId
     * @return String
     */
    @Override
    public String getLevelCombox(String deptId) {
        List<Map<String,String>> dataMap = commonBasicMapper.getLevelCombox(deptId);
        return JsonUtil.toText(dataMap);
    }

    /**
     * 系统管理 - 部门管理 - 部门管理 - 生成数据库不重复的最大部门ID
     * @param id 原始id
     * @param step 自增步数
     * @return int
     */
    private int getNoExistsId(int id,int step) {
        //判断i是否存在
        boolean flag = true;
        while(flag) {
            Department department = departmentMapper.selectByDeptId(String.valueOf(id));
            if(null != department) {
                id += step;
            } else {
                flag = false;
            }
        }
        return id;
    }

    /**
     * 系统管理 - 部门管理 - 部门管理 - 添加社矫部门
     * @param department department
     */
    private void saveSj(Department department) {
        if(null != department) {
            //03司法所、08区县司法局、07地市司法局、06司法厅
            //05社矫中心、14区县社矫、11地市社矫、15省社矫机构
            Department dep = new Department();
            String level = department.getLevel();
            String name = department.getName();
            String id = department.getId() + "X";
            String pid = department.getPid() + "X";
            dep.setId(id);
            if(Constants.OrgLevel.LEVEL_SFS.equals(level)) {
                dep.setName(name.replaceAll("司法所","社矫中心"));
                dep.setLevel(Constants.OrgLevel.LEVEL_SJZX);
            } else if(Constants.OrgLevel.LEVEL_QXSFJ.equals(level)) {
                dep.setName(name.replaceAll("司法局","社矫机构"));
                dep.setLevel(Constants.OrgLevel.LEVEL_QXSJ);
            } else if(Constants.OrgLevel.LEVEL_DSSFJ.equals(level)) {
                dep.setName(name.replaceAll("司法局","社矫机构"));
                dep.setLevel(Constants.OrgLevel.LEVEL_DSSJ);
            } else if(Constants.OrgLevel.LEVEL_SFT.equals(level)) {
                dep.setName(name.replaceAll("司法厅","社矫总队"));
                dep.setLevel(Constants.OrgLevel.LEVEL_SSJ);
                dep.setPid(pid);
            }
            dep.setPid(pid);
            dep.setStat(1);
            Integer count = departmentMapper.selectCount(new QueryWrapper<Department>().eq("id",dep.getId()));
            if(count == 0) {
                //添加社矫部门
                departmentMapper.insert(dep);
            }
        }
    }

    /**
     * 创建接口账号
     * @param department department
     */
    @Transactional(rollbackFor = Exception.class)
    public void createAccount(Department department) {
        UserInterFaceEntity userInterface = new UserInterFaceEntity();
        User sfUser = new User();
        User sjUser = new User();
        AuthUser sfAuthUser = new AuthUser(password,1);
        AuthUser sjAuthUser = new AuthUser(password,1);
        String username = "";
        String usernameStr = createUsername(department,username);
        try {
            //=============================单位编码  设置单位编码 ==============================
            sfUser.setDepartid(department.getId());
            sfUser.setOrgid(department.getPid());
            sfUser.setStat(1);
            sjUser.setDepartid(department.getId() + "X");
            sjUser.setOrgid(department.getPid() + "X");
            sjUser.setStat(1);
            if(department.getLevel().equals(Constants.OrgLevel.LEVEL_DSSFJ) || department.getLevel()
                                                                                         .equals(Constants.OrgLevel.LEVEL_QXSFJ)) {
                //=============================司法账号   地市、区县 ==============================
                usernameStr += "司法局";
                String sfaccount = checkAccount(PinYinUtils.getFirstSpell(usernameStr));
                sfUser.setAccount(sfaccount);
                sfUser.setUsername(department.getName() + "管理用户");
                if(department.getLevel().equals(Constants.OrgLevel.LEVEL_DSSFJ)) {
                    sfUser.setPosition("AB03");
                    sfUser.setRoleid(Constants.RoleId.ROLE_ID_DSSFJ);
                } else {
                    sfUser.setPosition("AB05");
                    sfUser.setRoleid(Constants.RoleId.ROLE_ID_QXSFJ);
                }
                //=============================社矫账号   地市、区县 ==============================
                String sjaccount = checkAccount(PinYinUtils.getFirstSpell(usernameStr.replace("司法局","社矫机构")));
                sjUser.setAccount(sjaccount);
                sjUser.setUsername(department.getName().replace("司法局","社矫机构") + "管理用户");
                if(Constants.OrgLevel.LEVEL_DSSFJ.equals(department.getLevel())) {
                    sjUser.setPosition("AB21");
                    sjUser.setRoleid(Constants.RoleId.ROLE_ID_DSSJ);
                } else {
                    sjUser.setPosition("AB27");
                    sjUser.setRoleid(Constants.RoleId.ROLE_ID_QXSJ);
                }
            } else if(department.getLevel().equals(Constants.OrgLevel.LEVEL_SFS)) {
                //=============================司法账号   司法所 ==============================
                String sfaccount = checkAccount(PinYinUtils.getFirstSpell(usernameStr));
                sfUser.setAccount(sfaccount);
                sfUser.setUsername(department.getName() + "管理用户");
                sfUser.setPosition("AB07");
                sfUser.setRoleid(Constants.RoleId.ROLE_ID_SFS);
                //=============================社矫账号   社矫中心 ==============================
                String sjaccount = checkAccount(PinYinUtils.getFirstSpell(usernameStr.replace("司法所","社矫中心")));
                sjUser.setAccount(sjaccount);
                sjUser.setUsername(department.getName().replace("司法所","社矫中心") + "管理用户");
                sjUser.setPosition("AB17");
                sjUser.setRoleid(Constants.RoleId.ROLE_ID_SJZX);
                //============================= 社矫接口用户创建 ==============================
                userInterface.setAccount(sjUser.getAccount());
                userInterface.setDepartid(sjUser.getDepartid());
                userInterface.setOrgid(sjUser.getOrgid());
                userInterface.setPosition(sjUser.getPosition());
                userInterface.setRoleid(sjUser.getRoleid());
                userInterface.setUid(Constants.USER_INTERFACE_UID);
                userInterface.setUsername(sjUser.getUsername().replace("管理用户","接口用户"));
            }
            //=============================auth用户 司法  账号密码 ==============================
            sfAuthUser.setAccount(sfUser.getAccount());
            //=============================auth用户 社矫  账号密码 ==============================
            sjAuthUser.setAccount(sjUser.getAccount());
            // 开始执行插入
            sfUser.insert();
            sjUser.insert();
            // 非司法所账号生成的社矫机构人员信息，不得插入接口用户表
            if(department.getLevel().equals(Constants.OrgLevel.LEVEL_SFS)) {
                commonBasicMapper.insertTbsysUserInface(userInterface);
            }
            commonBasicMapper.insertAuthUser(sfAuthUser);
            commonBasicMapper.insertAuthUser(sjAuthUser);
        } catch(Exception e) {
            log.error(e.getMessage());
        }
    }

    /**
     * 获取本省下所有监狱
     * @param id id
     * @return List<Department>
     */
    @Override
    public List<Department> getAllPrison(String id) {
        String pid = id.substring(0,4);
        return departmentMapper.selectList(new QueryWrapper<Department>().eq("pid",pid));
    }

    /**
     * 循环遍历，获取单位名称
     * 格式   XX省_XX市_XX区_XX街道
     * @param department department
     * @param username username
     * @return String
     */
    private String createUsername(Department department,String username) {
        // 循环遍历，拼接单位名称信息
        if(department != null && !Constants.NumberStr.NUM_STR_TEN.equals(department.getLevel()) && !Constants.NumberStr.NUM_STR_ONE.equals(department.getLevel())) {
            username = "_" + department.getName() + username;
            Department departmentPar = departmentMapper.selectByDeptId(department.getPid());
            if(departmentPar != null && !Constants.NumberStr.NUM_STR_TEN.equals(departmentPar.getLevel())) {
                return createUsername(departmentPar,username);
            }
        }
        // 替换不需要的字符名称
        username = username.replace("社矫总队","").replace("社矫管理局","").replace("司法厅","").replace("司法局","")
                           .replace("社矫机构","").replace("地市","").replace("区县","").replaceFirst("_","");
        return username;
    }

    /**
     * 查看账号是否已经存在，如果存在，加序号
     * 如：xxsfj1  xxsfj2
     * @param account account
     * @return String
     */
    private String checkAccount(String account) {
        Long total = userMapper.checkAccount(account);
        if(total > 0) {
            account += total;
        }
        return account;
    }

    /**
     * 预安置管理 - 全部人员管理-入监单位
     * @param departId departId
     * @return List<Map<String,String>>
     */
    @Override
    public List<Map<String,String>> getrjdanwei(String departId) {
        return departmentMapper.getrjdanwei(departId);
    }

    /**
     * 根据ID查询部门信息
     * @param id id
     * @return Department
     */
    public Department selectByDeptId(String id) {
        return departmentMapper.selectByDeptId(id);
    }
}